package com.tanhua.dubbo.huanxin.api.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.api.HuanXinApi;
import com.tanhua.dubbo.enums.HuanXinMessageType;
import com.tanhua.dubbo.huanxin.config.HuanXinConfig;
import com.tanhua.dubbo.huanxin.mapper.HuanXinUserMapper;
import com.tanhua.dubbo.huanxin.service.RequestService;
import com.tanhua.dubbo.huanxin.service.TokenService;
import com.tanhua.dubbo.pojo.HuanXinUser;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

@DubboService(version = "1.0.0")
public class HuanXinApiImpl implements HuanXinApi {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private HuanXinUserMapper huanXinUserMapper;

    @Autowired
    private RequestService requestService;

    @Override
    public String getToken() {
        return this.tokenService.getToken();
    }

    /**
     * 注册环信用户
     * 参见：http://docs-im.easemob.com/im/server/ready/user#%E6%B3%A8%E5%86%8C%E5%8D%95%E4%B8%AA%E7%94%A8%E6%88%B7_%E5%BC%80%E6%94%BE
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public Boolean register(Long userId) {
        //定义url
        String url = StrUtil.format("{}{}/{}/users",
                this.huanXinConfig.getUrl(),
                this.huanXinConfig.getOrgName(),
                this.huanXinConfig.getAppName());

        //请求参数
        Map<Object, Object> requestParam = MapUtil.builder()
                .put("username", "HX_" + userId) //用户名
                .put("password", IdUtil.simpleUUID()) //密码
                .put("nickname", "HX_" + userId) //昵称
                .build();

        HttpResponse httpResponse = this.requestService.execute(Method.POST, url, JSONUtil.toJsonStr(Arrays.asList(requestParam)));

        if (httpResponse.isOk()) {
            //注册用户到环信成功 , 需要存储到mysql中
            HuanXinUser huanXinUser = BeanUtil.toBeanIgnoreError(requestParam, HuanXinUser.class);
            huanXinUser.setUserId(userId);
            huanXinUser.setCreated(new Date());
            huanXinUser.setUpdated(huanXinUser.getCreated());
            return this.huanXinUserMapper.insert(huanXinUser) == 1;
        }

        if (httpResponse.getStatus() == 400) {
            //参数不合法 或 用户名已经存在
            return false;
        }

        return false;
    }

    /**
     * 根据用户Id询环信账户信息
     *
     * @param userId
     * @return
     */
    @Override
    public HuanXinUser queryHuanXinUser(Long userId) {
        QueryWrapper<HuanXinUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return this.huanXinUserMapper.selectOne(queryWrapper);
    }

    @Override
    public HuanXinUser queryHuanXinUserByUserName(String userName) {
        QueryWrapper<HuanXinUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        return this.huanXinUserMapper.selectOne(queryWrapper);
    }

    /**
     * 添加好友（双向好友关系）
     * 参见：http://docs-im.easemob.com/im/server/ready/user#%E6%B7%BB%E5%8A%A0%E5%A5%BD%E5%8F%8B
     *
     * @param userId   自己的id
     * @param friendId 好友的id
     * @return
     */
    @Override
    public Boolean addUserFriend(Long userId, Long friendId) {
        String url = StrUtil.format("{}{}/{}/users/{}/contacts/users/{}",
                this.huanXinConfig.getUrl(),
                this.huanXinConfig.getOrgName(),
                this.huanXinConfig.getAppName(),
                "HX_" + userId,
                "HX_" + friendId);

        HttpResponse httpResponse = this.requestService.execute(Method.POST, url, null);
        if (httpResponse.isOk()) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean removeUserFriend(Long userId, Long friendId) {
        String url = StrUtil.format("{}{}/{}/users/{}/contacts/users/{}",
                this.huanXinConfig.getUrl(),
                this.huanXinConfig.getOrgName(),
                this.huanXinConfig.getAppName(),
                "HX_" + userId,
                "HX_" + friendId);

        HttpResponse httpResponse = this.requestService.execute(Method.DELETE, url, null);
        if (httpResponse.isOk()) {
            return true;
        }
        return false;
    }

    /**
     * 以管理员身份发送消息
     * 文档地址：http://docs-im.easemob.com/im/server/basics/messages#%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AF
     *
     * @param targetUserName     发送目标的用户名
     * @param huanXinMessageType 消息类型
     * @param msg
     * @return
     */
    @Override
    public Boolean sendMsgFromAdmin(String targetUserName, HuanXinMessageType huanXinMessageType, String msg) {
        String url = StrUtil.format("{}{}/{}/messages",
                this.huanXinConfig.getUrl(),
                this.huanXinConfig.getOrgName(),
                this.huanXinConfig.getAppName());

        //请求参数
        String param = JSONUtil.toJsonStr(MapUtil.builder()
                .put("target_type", "users")
                .put("target", Arrays.asList(targetUserName))
                .put("msg", MapUtil.builder()
                        .put("type", huanXinMessageType.getType())
                        .put("msg", msg)
                        .build())
                .put("from", "admin")
                .build());

        HttpResponse httpResponse = this.requestService.execute(Method.POST, url, param);
        if (null == httpResponse) {
            return false;
        }
        return httpResponse.isOk();
    }
}
